package com.tool.payment.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tool.payment.enums.ModeEnum;
import com.tool.payment.service.PaymentProxyService;
import com.tool.payment.util.QRUtil;

@Controller
@RequestMapping("pay/{product}")
public class PayController {
	
	@Autowired
	private PaymentProxyService proxyService;
	
	
	@RequestMapping(value="dopay")
	public void dopay(@PathVariable("product") String product,
			HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String mode = request.getParameter("mode");
		Map<String, String> result = proxyService.createOrder(product, mode, request);
		if(mode.equals(ModeEnum.NATIVE.name)) {
			PrintWriter writer = response.getWriter();
            writer.write(result.get("html"));
            writer.close();
		}
	}
	
	/**
	 * 处理不需要跳转订单(如微信公众号等移动端支付)
	 * @param product weixin、alipay
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="notview")
	@ResponseBody
	public Map<String, String> notview(@PathVariable("product") String product,
											HttpServletRequest request,HttpServletResponse response) {
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		String mode = request.getParameter("mode");
		Map<String, String> result = proxyService.createOrder(product, mode, request);
		return result;
	}
	
	@RequestMapping(value="dopayqr")
	public void doPayQR(String codeurl, HttpServletResponse response) {
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		QRUtil.createQRcode(codeurl, null, 500, response);
	}
}
